using EIMS.Data;
using EIMS.Models.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Serilog.Events;
using AutoMapper;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
using OfficeOpenXml;

namespace EIMS
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
         
            
            var builder = WebApplication.CreateBuilder(args);

            // 优化日志配置，减少性能开销
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.File("logs/eims-.log", rollingInterval: RollingInterval.Day, 
                    restrictedToMinimumLevel: LogEventLevel.Warning)
                .CreateLogger();

            builder.Host.UseSerilog();

            // 添加数据库服务，配置连接池
            builder.Services.AddDbContext<ApplicationDbContext>(options => {
                options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
                options.EnableSensitiveDataLogging(false); // 禁用敏感数据日志
                options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); // 默认使用无跟踪查询
            });

            // 添加 Identity 服务
            builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                // 密码设置
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 6;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase = true;
                options.Password.RequireLowercase = true;

                // 用户设置
                options.User.RequireUniqueEmail = true;
                
                // 登录设置
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedAccount = false;
                
                // 锁定设置
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 5;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // 配置 Cookie 设置
            builder.Services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";
                options.AccessDeniedPath = "/Account/AccessDenied";
                options.SlidingExpiration = true;
                options.ExpireTimeSpan = TimeSpan.FromHours(3);
                
                // 优化Cookie性能
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
                
                // 这将减少每个请求的数据库查询
                options.Cookie.Name = "EIMS.AuthCookie";
            });
            
            // 添加缓存支持
            builder.Services.AddMemoryCache();
            builder.Services.AddDistributedMemoryCache();
            
            // 添加响应缓存中间件（修复VaryByQueryKeys错误）
            builder.Services.AddResponseCaching();
            
            // 添加响应压缩
            builder.Services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
                options.Providers.Add<GzipCompressionProvider>();
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/javascript", "text/css", "application/xml", "text/html" });
            });
            
            builder.Services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = System.IO.Compression.CompressionLevel.Fastest;
            });

            // 添加 AutoMapper
            builder.Services.AddAutoMapper(typeof(AutoMapperProfile).Assembly);

            // 优化控制器配置
            builder.Services.AddControllersWithViews(options => {
                options.CacheProfiles.Add("Default", new Microsoft.AspNetCore.Mvc.CacheProfile 
                { 
                    Duration = 60, // 缓存60秒
                    Location = Microsoft.AspNetCore.Mvc.ResponseCacheLocation.Any
                });
            })
            .AddJsonOptions(options => {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
            });
            
            // 添加HTTP上下文访问器
            builder.Services.AddHttpContextAccessor();

            var app = builder.Build();

            // 使用响应压缩
            app.UseResponseCompression();
            
            // 使用响应缓存中间件
            app.UseResponseCaching();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            else
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            
            // 静态文件缓存1天
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 86400;
                    ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = 
                        "public,max-age=" + durationInSeconds;
                }
            });

            app.UseRouting();

            // 添加认证和授权中间件
            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            // 初始化数据库 - 创建EF Core迁移并应用
            using (var scope = app.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ApplicationDbContext>();
                    
                    // 确保数据库已创建
                    context.Database.EnsureCreated();
                    
                    // 如果没有用户表，则运行初始化程序
                    bool needsInitialization = false;
                    
                    try 
                    {
                        // 尝试访问用户表，如果表存在但没有数据，返回false
                        needsInitialization = !context.Users.Any();
                    }
                    catch 
                    {
                        // 表不存在，需要初始化
                        needsInitialization = true;
                    }
                    
                    if (needsInitialization)
                    {
                        await DbInitializer.InitializeAsync(services);
                    }
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "初始化数据库时发生错误");
                }
            }

            app.Run();
        }
    }
}
